package com.huadi.cmcc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huadi.cmcc.domain.Order;
import com.huadi.cmcc.domain.Result;
import com.huadi.cmcc.domain.Shopcar;
import com.huadi.cmcc.domain.User;
import com.huadi.cmcc.service.OrderService;
import com.huadi.cmcc.service.ShopcarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author lzc
 * @date 2021/8/25
 */
@RestController
@RequestMapping("/shopcar")
public class ShopCarController {
    @Autowired
    private ShopcarService shopcarService;
    @Autowired
    private OrderService orderService;
    /*
    * 移动套餐添加到购物车
    */
    @PostMapping("save")
    public Result save(Shopcar shopcar, HttpSession session) {
        shopcar.setId(null);
        //获取用户id添加到对应的购物车项中
        final User user = (User) session.getAttribute("user");
        shopcar.setUserid(user.getId());
        shopcarService.save(shopcar);
        return Result.success();
    }

    @GetMapping("/page")
    public Result<Page<Shopcar>> page(Page<Shopcar> page, String packageName, HttpSession session) {
        final User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Page<Shopcar> resultPage = shopcarService.listByPage(page, packageName, user.getId());
        return Result.success(resultPage);
    }

    /**
     * 充值
     * @return
     */
    @GetMapping("/deposit")
    public Result deposit(Long id, Long packageid, HttpSession session) {
        final User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("用户未登录");
            return Result.fail("用户未登录");
        }
        //生成订单
        Order order = new Order();
        order.setUserid(user.getId());
        order.setPackageid(packageid);
        order.setTime(new Date());
        orderService.save(order);
        //删除购物车
        shopcarService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        shopcarService.removeById(id);
        return Result.success();
    }
}
